<template>
  <a-alert  type="info" class="a-alert-wrap">
    <template v-slot:message>
      <div class="wrap-div">
        <div class="left-box">
          <span className="wrap-span">
            <CheckCircleFilled style="font-size: 16px, font-weight: bold, margin-right:6px"/>
            已选择 <span class="wrap-span-text"> {{ tableConfig.rowSelection.selectedRowKeys.length }} </span> 项
            <span class="wrap-span-clear" @click="tableConfig.rowSelection.selectedRowKeys = []">清空</span>
            <a-divider type="vertical" style='border-left: 1px solid rgba(0, 0, 0, 0.2)'/>
          </span>
          <slot name="toolbarContent"></slot>
        </div>
        <div class="right-box">
          <a-tooltip placement="top" title="刷新">
            <ReloadOutlined className="icon-self-style" />
          </a-tooltip>
          <a-popover  title='自定义列' placement="rightBottom" trigger="click">
            <a-tooltip placement="top" title="列设置">
              <SettingOutlined  style="margin-left: 10px" />
            </a-tooltip>
          </a-popover>
        </div>
      </div>
    </template>
  </a-alert>
  <a-table 
    :id="tableId"
    ref="refTable"
    v-bind="attrs" 
    @resizeColumn="handleResizeColumn"
    :columns="tableColumns"  
    :loading="tableConf.loading"
    @change="(...args) => {tableConf.change && tableConf.change(...args)}"
    :pagination="Object.assign({}, paginationDefaultConfig,tableConf.pagination)"
    :row-selection="tableConf.rowSelection"
    :customRow="customRowFunc"
    size="small"
    :scroll="tableScroll" 
    :rowKey="rowKey"
    :data-source="tableConf.dataList">
    <template #headerCell="item">
      <slot name="headerCell" v-bind="item"></slot>
    </template>
    <template #bodyCell="item">
      <slot name="bodyCell" v-bind="item"></slot>
    </template>
    <template #buildOptionText="props">
      <span>{{ props.value }}条/页</span>
    </template>
  </a-table>
</template>

<script>
import { toRaw, reactive, readonly, isReadonly, onMounted,ref } from 'vue'
import { SettingOutlined, ReloadOutlined, CheckCircleFilled } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
export default {
  components: {SettingOutlined, ReloadOutlined, CheckCircleFilled},
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    scroll: {
      type: Object,
      default: () => ({})
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    dataSource: {
      type: Array,
      default: () => []
    },
    tableConfig: {
      type: Object,
      default: () => ({
        dataList: [],
        loading: false,
        pagination: {
          total: 0,
          current: 1,
          pageSize: 20,
        },
        rowSelection: {
          type: 'checkbox ',      //  checkbox  -- 多选 ， radio -- 单选
          selectedRowKeys: [],
          onChange: () => {}
        },
        change: {
          type: Function,
          default: () => {}
        },
        customRow: {
          onClick(event){},
          onDblclick: (event) => {},
          onContextmenu: (event) => {},
          onMouseenter: (event) => {},  // 鼠标移入行
          onMouseleave: (event) => {}
        }
      })
    },
  },
  setup({ columns, scroll, tableConfig, rowKey }, {attrs,emit, expose,  slots}){

    const tableId = $g.nanoid()
    const refTable = ref(null)
    const tableScroll = reactive({})

    onMounted(() => {

      const dom = document.getElementById(tableId)

      const {left , top } = dom.getBoundingClientRect()

      'y' in scroll ? tableScroll.y = scroll.y : tableScroll.y = `calc(100vh - ${ top + 108 }px)`
      'x' in scroll ? tableScroll.x = scroll.x : tableScroll.x = 0

    })

    let tableColumns = $g.cloneDeep(columns)
    tableColumns.forEach(r => {
      r.resizable = true
      r.ellipsis=true
    })
    tableColumns = reactive(tableColumns)

    let paginationDefaultConfig = {
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      showTotal: total => `共 ${total} 条`
    }

    const { customRow = {} } = tableConfig || {}
    const customRowFunc = (row, index) => {
      const item = {}
      if( customRow !== null && typeof customRow === 'object' ){    // 如果 有 customRow 对象
        const list = ['onClick', 'onDblclick','onContextmenu','onMouseenter','onMouseleave']
        list.forEach(r => {
          if( r === 'onClick' ){
            item[r] = (event) => {

              // 默认多选 吧  checkbox -- 多选    radio -- 单选
              const { selectedRowKeys, selectedRows = [], type = 'checkbox' } = tableConfig.rowSelection || {}
              if( Array.isArray(selectedRowKeys) ){
                const id = row[rowKey] || ''

                const i = selectedRowKeys.findIndex(g => g === id)

                if( type === 'checkbox' ){    // 如果是多选
                  i === -1 ? (selectedRowKeys.push(id)) : (selectedRowKeys.splice(i, 1))
                  i === -1 ? (selectedRows.push(row)) : (selectedRows.splice(i, 1))
                }else if(type === 'radio'){   // 如果 是 单选
                  if( i === -1 ){
                    selectedRowKeys.splice(0, 1, id)
                    selectedRows.splice(0, 1, row)
                  }
                }
              }
              if( typeof customRow[r] === 'function' ) customRow[r](row, index, event)
            }
          }else if( typeof customRow[r] === 'function' ){
            item[r] = (event) => customRow[r](row, index, event)
          }
        })
      }
      return item
    }

    if(tableConfig && tableConfig.rowSelection){

      const { onChange } = tableConfig.rowSelection     //存好 之前 传入的 onChange 回调函数
      tableConfig.rowSelection.onChange = (selectedRowKeys, selectedRows) => {
        tableConfig.rowSelection.selectedRowKeys = selectedRowKeys
        tableConfig.rowSelection.selectedRows = selectedRows
        typeof onChange === 'function' && onChange(selectedRowKeys, selectedRows)
      }

      if( !('preserveSelectedRowKeys' in tableConfig.rowSelection) ){
        tableConfig.rowSelection.preserveSelectedRowKeys = true       //  默认 true, 当数据被删除时仍然保留选项的 key  --  跨页 勾选
      }

      if( !('type' in tableConfig.rowSelection) ){
        tableConfig.rowSelection.type = 'checkbox'    //  checkbox -- 多选   radio -- 单选
      }

    }

    return {
      customRowFunc,
      paginationDefaultConfig,
      tableColumns,
      tableConf: tableConfig,
      attrs,
      tableId,
      refTable,
      tableScroll,
      handleResizeColumn: (w, col) => {
        col.width = w;
      }
    }
  }
}
</script>

<style scoped lang="less">
.a-alert-wrap{
  padding: 2px 15px;
  margin-bottom: 4px;
  border-radius: 2px !important;
  background-color: #f1f1f1 !important;
  border: 1px solid #d8d7d7 !important;
  .wrap-div{
    height: 26px;
    display: flex;
    .left-box{
      flex: 1 1;
      display: flex;
      align-items: center;
      .wrap-span{
        color: #677170;
        .wrap-span-text{
          font-weight: bold;
          color: #1aa391;
        }
        .wrap-span-clear{
          color: #1aa391;
          cursor: pointer;
          margin-left: 12px;
          margin-right: 2px;
        }
      }
    }
    .right-box{
      width: auto;
      align-items: center;
      display: flex;
      // margin-left: 10px;
      font-size: 16px;
      cursor: pointer;
      span{
        &:hover{
          color: #009688;
        }
      }
    }
  }
}
</style>